from __future__ import print_function
import os.path
import base64
import socket
from email.mime.text import MIMEText
import httplib2

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# 设置全局超时
socket.setdefaulttimeout(30)

SCOPES = ['https://www.googleapis.com/auth/gmail.send']

def build_service(creds):
    """创建带超时设置的Gmail服务"""
    http = httplib2.Http(timeout=30)
    authorized_http = creds.authorize(http)
    return build('gmail', 'v1', http=authorized_http)

def create_message(sender, to, subject, message_text):
    """创建一封邮件"""
    message = MIMEText(message_text)
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject
    return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}

def send_message(service, user_id, message):
    """发送邮件"""
    try:
        message = (service.users().messages().send(userId=user_id, body=message)
                   .execute())
        print(f'Message Id: {message["id"]}')
        return message
    except socket.timeout:
        print("请求超时，请检查网络连接")
        return None
    except HttpError as error:
        print(f'API错误: {error}')
        return None

def main():
    """发送测试邮件"""
    creds = None
    token_path = './google-api/token.json'
    
    if os.path.exists(token_path):
        creds = Credentials.from_authorized_user_file(token_path, SCOPES)
    
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            try:
                creds.refresh(Request())
            except Exception as e:
                print(f"刷新令牌失败: {e}")
                os.remove(token_path)
                flow = InstalledAppFlow.from_client_secrets_file(
                    './google-api/credentials.json', SCOPES)
                creds = flow.run_local_server(port=9099)
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                './google-api/credentials.json', SCOPES)
            creds = flow.run_local_server(port=9099)
        
        with open(token_path, 'w') as token:
            token.write(creds.to_json())

    try:
        service = build_service(creds)
        
        sender = "me"
        to = "junh88888888@gmail.com"
        subject = "测试邮件"
        message_text = "这是一封通过Gmail API发送的测试邮件。"
        
        message = create_message(sender, to, subject, message_text)
        result = send_message(service, "me", message)
        if result:
            print("邮件发送成功!")
        
    except Exception as e:
        print(f'发生错误: {e}')

if __name__ == '__main__':
    main()